package com.example.no1admin.service.impl;

import com.example.no1admin.ex.ServiceException;
import com.example.no1admin.mapper.CommentsMapper;
import com.example.no1admin.pojo.dto.comments.CommentsAddNewDTO;
import com.example.no1admin.pojo.entity.Comments;
import com.example.no1admin.pojo.vo.comments.CommentsDetailVO;
import com.example.no1admin.pojo.vo.comments.CommentsListItemVO;
import com.example.no1admin.service.ICommentsService;
import com.example.no1admin.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class CommentsServiceImpl implements ICommentsService {
    
    @Autowired
    CommentsMapper commentsMapper;
    
    public CommentsServiceImpl() {
        log.debug("创建业务逻辑对象：CommentsServiceImpl");
    }

    @Override
    public void addNew(CommentsAddNewDTO commentsAddNewDTO) {
        log.debug("准备开始处理创建评论的业务，参数：{}",commentsAddNewDTO);

        //创建实体对象(mapper的方法参数是实体类型)
       Comments comments = new Comments();
        //将当前方法参数的值复制到Brand实体类型的对象中
        BeanUtils.copyProperties(commentsAddNewDTO,comments);
        //补全属性值(不由客户端提交的属性的值，应该在插入之前补全)

        //将评论数据写入到数据库
        log.debug("即将向表中插入数据：{}",comments);
        int rows = commentsMapper.insert(comments);
        if(rows!=1){
            String message = "创建评论失败，服务器忙，请稍后再试!";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }

    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理删除评论的业务,id={}",id);
        CommentsDetailVO comments = commentsMapper.getById(id);
        if(comments==null){
            String message = "删除评论失败，尝试删除的数据【"+id+"】不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        int rows = commentsMapper.deleteById(id);
        if(rows!=1){
            String message = "删除评论失败，服务器忙，请稍后再试!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }
    }
    
    @Override
    public List<CommentsListItemVO> list() {
        log.debug("开始处理查询评论列表的请求");
        return commentsMapper.list();
    }
}
